import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shop/tools/httpsClient.dart';

import '../../../../models/plistModel.dart';

class ProductListController extends GetxController {
  //TODO: Implement ProductListController

  RxList<plistItemModel> pList = <plistItemModel>[].obs;
  RxInt page = 1.obs;
  int pageSize = 8;
  HttpsClient httpsClient = HttpsClient();

  // 获取传值
  String? keyWords = Get.arguments['keyWords'];
  String? cid = Get.arguments['cid'];
  String apiUrl = '';

  // 添加滚动监听
  ScrollController scrollController = ScrollController();
  bool flag = true;
  RxBool hasData = true.obs;

  // 筛选弹出drawer
  GlobalKey<ScaffoldState> scaffoldGlobal = GlobalKey();

  // 二级导航数据
  List subHeaderList = [
    {"id": 1, "title": "综合", "fileds": "all", "sort": -1},
    {"id": 2, "title": "销量", "fileds": "salecount", "sort": -1},
    {"id": 3, "title": "价格", "fileds": "price", "sort": -1},
    {"id": 4, "title": "筛选"},
  ]; //升序 price_1 降序 price_-1
  String sort = '';

  // 二级导航选中判断
  RxInt selectHeaderId = 1.obs;

  // 二级导航改变时触发方法
  void subHeaderChange(id) {
    if (id == 4) {
      scaffoldGlobal.currentState!.openEndDrawer();
      selectHeaderId.value = id;
    } else {
      selectHeaderId.value = id;
      //   改变排序
      sort =
          "${subHeaderList[id - 1]['fileds']}_${subHeaderList[id - 1]['sort']}";
      subHeaderList[id - 1]['sort'] = subHeaderList[id - 1]['sort'] * -1;
      //重置page
      page.value = 1;
      // 重置plist
      pList.value = [];
      //
      hasData.value = true;
      // 滚动条回到顶部
      scrollController.jumpTo(0);
      //   重新请求接口
      getPListData();
    }
  }

  @override
  void onInit() {
    super.onInit();
    getPListData();
    scrollControllerListener();
  }

  @override
  void onClose() {
    super.onClose();
  }

  scrollControllerListener() {
    scrollController.addListener(() {
      // scrollController.position.pixels//这是滚动的距离
      // scrollController.position.maxScrollExtent//这是最大距离
      if (scrollController.position.pixels >
          (scrollController.position.maxScrollExtent - 20)) {
        getPListData();
      }
    });
  }

  void getPListData() async {
    if (flag && hasData.value) {
      flag = false;
      if (cid != null) {
        apiUrl =
            '/api/plist?cid=${cid}&page=${page.value}&pageSize=${pageSize}&sort=${sort}';
      } else {
        apiUrl =
            '/api/plist?search=${keyWords}&page=${page.value}&pageSize=${pageSize}&sort=${sort}';
      }
      print('获得cid${Get.arguments['cid']}');
      print('获得cid${Get.arguments['keyWords']}');
      var response = await httpsClient.get(apiUrl);
      if (response != null) {
        var pListTemp = plistModel.fromJson(response.data);
        pList.addAll(pListTemp.result!);
        print('获得对应种类的数据${pList}');
        page++;
        update();
        flag = true;
        if (pListTemp.result!.length < pageSize) {
          hasData.value = false;
        }
      }
    }
  }
}
